import vueStat from 'stat/vue'
import { GetSdkData } from 'stat/client'

// 万年历客户端埋点上报
export default (
	router, 
	{
		showConsole = false,
		oncePageView = false,
		onceNodeView = true,
		metaPageName = 'cnzz',
		metaPageParamsGet = 'getParams',
		isWnl = false,
	}
) => ({
	install(vue) {
		const getSdkData = GetSdkData(vue)
		let hostSdk
		try {
			if (!isWnl) throw new Error('not isWnl')
			hostSdk = require('host-sdk')
		} catch (err) {
			console.log(`%c ${err}`, 'color: red;')

			hostSdk = {
				setShareParam() { console.log('%c setShareParam not wnl!', 'color: red;') },
                stat_wnl() { console.log('%c stat_wnl not wnl!', 'color: red;') },
                uploadPageEndStatistics() { console.log('%c uploadPageEndStatistics not wnl!', 'color: red;') },
			}
		}

		vueStat.set({
			from: 'wnl',
			router,
			metaPageName,
			metaPageParamsGet,
			report: (data, opt) => {
				const _data = getSdkData(data)

                showConsole && console.log(`%c${_data}`, 'color: blue;')

                hostSdk.stat_wnl(_data, opt)
			},
			oncePageView,
			onceNodeView,
		})
		vue.use(vueStat)

		// 消费来源统计
		vue.prototype.$setShareParam = data => {
			showConsole && console.log('%c $setShareParam', 'color: blue;', data)

			const { bookId, method, param } = data

			hostSdk.setShareParam({ data: { sourceType: 0, param, 'book_id': bookId || '', method: method || 1 } })
		}

		// 页面跳转时间统计
		let time = Date.now()
		let time2 = 0
		let diff = 0
		let count = 0
		const updateTime = () => {
			time2 = Date.now()
			diff = time2 - time
			time = time2

			return true
		}
		const getDiffData = () => ({ pageName: JSON.parse(getSdkData())[0].parentPage, duration: diff })

		router.afterEach(() => count++ && setTimeout(() => updateTime() && hostSdk.uploadPageEndStatistics(getDiffData()), 200))
	}
})
